// 封装 fetch 函数
const fetchData = async (url, options = {}) => {
  try {
    const response = await fetch(url, options);

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const contentType = response.headers.get("content-type");
    if (contentType && contentType.includes("application/json")) {
      return await response.json();
    } else {
      return await response.text();
    }
  } catch (error) {
    console.error('Fetch error:', error);
    throw error;
  }
};

// 发送 GET 请求
const get = async (url) => {
  console.log(fetchData(url, {
    method: 'GET'
  }), url);
  return fetchData(url, {
    method: 'GET'
  });
};

// 发送 POST 请求
const post = async (url, data) => {
  return fetchData(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
  });
};

// 发送 PUT 请求
const put = async (url, data) => {
  return fetchData(url, {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
  });
};

// 发送 DELETE 请求
const del = async (url) => {
  return fetchData(url, { method: 'DELETE' });
};

export default { get, post, put, del }